define(["jquery", "easy-admin", "xm-select","treetable", "iconPickerFa", "autocomplete"], function ($, ea) {
    let laydate = layui.laydate
        , form = layui.form
        , upload  = layui.upload,
        treetable = layui.treetable,
        iconPickerFa = layui.iconPickerFa,
        autocomplete = layui.autocomplete;
    var init = {
        table_elem: '#currentTable',
        table_render_id: 'currentTableRenderId',
        index_url: 'machine.machine/index',
        add_url: 'machine.machine/add',
        edit_url: 'machine.machine/edit',
        delete_url: 'machine.machine/delete',
        export_url: 'machine.machine/export',
        modify_url: 'machine.machine/modify',
        async_url:'machine.machine/asyncMachine',
        authorization_url:'machine.machine/authorization',
        seasoning_url:'machine.machineSeasoning/index'
    };

    var Controller = {
        index: function () {
            ea.table.render({
                init: init,
                toolbar: ['refresh',
                    [{
                        text: '添加',
                        url: init.add_url,
                        method: 'open',
                        auth: 'add',
                        class: 'layui-btn layui-btn-normal layui-btn-sm',
                        icon: 'fa fa-plus ',
                        extend: 'data-full="true"',
                    }],
                    'delete', 'export'],
                minWidth: 90,
                cols: [[
                    {type: 'checkbox'},
                    {field: 'id', title: '机器ID', width: 90},
                    {field: 'machine_id', title: '机器编号', width: 150},
                    {field: 'snCode', title: '设备snCode', width: 150,edit:'text'},
                    {field: 'machine_name', title: '机器名称',width: 180},
                    {field: 'province_name', title: '所在省',width: 180},
                    {field: 'city_name', title: '所在市',width: 180,search: false},
                    {field: 'area_name', title: '所在区',width: 180},
                    {field: 'address', title: '详情地址',width: 180},
                    {field: 'machineCate.title', title: '所属代理商',search: false,width: 180},
                    {
                        field: 'status',
                        search: 'select',
                        selectList: ["禁用", "启用"],
                        title: '状态',
                        templet: ea.table.switch,
                        width: 100
                    },

                    {
                        field: 'state',
                        search: 'select',
                        selectList: {1: '正常', 2: '断网',3:'机器故障'},
                        title: '机器状态',
                        minWidth: 100
                    },
                    {field: 'create_time', title: '创建时间', search:'range',width: 180},
                    {
                        width: 250, title: '操作', templet: ea.table.tool, operat: [
                            [{
                                text: '授权规格',
                                extra: 'name',
                                url: init.authorization_url,
                                method: 'open',
                                auth: 'authorization',
                                class: 'layui-btn layui-btn-xs',
                                extend: 'data-full="true"',
                            },{
                                text: '授权口味',
                                extra: 'name',
                                url: init.seasoning_url,
                                method: 'open',
                                auth: 'authSeasoning',
                                class: 'layui-btn layui-btn-xs layui-btn-normal',
                                extend: 'data-full="true"',
                            },{
                                text: '编辑',
                                extra: 'name',
                                url: init.edit_url,
                                method: 'open',
                                auth: 'edit',
                                class: 'layui-btn layui-btn-xs layui-btn-success',
                                extend: 'data-full="true"',
                            }],
                            'delete']
                    },
                ]],
            });

            ea.listen();
        },
        add: function () {

            let machine_cate = xmSelect.render({
                el: '#machine_cate',
                radio: true,
                clickClose: true,
                toolbar: {show: true},
                name: 'machine_cate',
                paging: true,
                filterable: true,
                tips: '选择机器分组',
                data: [],
            });
            //获取支付方式
            $.get("/admin/machine.cate/getCateByList").then(res => {
                if (res.code == 1) {
                    machine_cate.update({
                        data: res.data
                    })
                }
            });
            let province = xmSelect.render({
                el: '#province',
                toolbar: {
                    show: true,
                },
                filterable: true,
                paging: true,
                pageSize: 10,
                data: [],
                radio: true,
                clickClose: true,
                name: 'province',
                on: function (data) {
                    let arr = data.arr,
                        isAdd = data.isAdd;
                    if (isAdd) {
                        $("#province_name").val(arr[0].name);
                        $.get("/admin/system.city/getProvinceByCityNameAndValue", {
                            province: arr[0].value
                        }).then(res => {
                            if (res.code == 1) {
                                city.update({
                                    data: res.data
                                })
                            }
                        })
                    }
                }
            })
            let city = xmSelect.render({
                el: '#city',
                toolbar: {
                    show: true,
                },
                filterable: true,
                paging: true,
                pageSize: 10,
                data: [],
                radio: true,
                clickClose: true,
                tips: '请选择省',
                name: 'city',
                on: function (data) {
                    let arr = data.arr,
                        isAdd = data.isAdd;
                    if (isAdd) {
                        $("#city_name").val(arr[0].name);
                        $.get("/admin/system.area/getCityByAreaNameAndValue", {
                            city: arr[0].value
                        }).then(res => {
                            if (res.code == 1) {
                                area.update({
                                    data: res.data
                                })
                            }
                        })
                    }
                }
            })
            let area = xmSelect.render({
                el: '#area',
                toolbar: {
                    show: true,
                },
                filterable: true,
                paging: true,
                pageSize: 10,
                data: [],
                radio: true,
                clickClose: true,
                tips: '请选择市',
                name: 'area',
                on: function (data) {
                    console.log(data)
                    let arr = data.arr,
                        isAdd = data.isAdd;
                    if(isAdd) {
                        $("#area_name").val(arr[0].name);
                    }
                }
            })
            let address = xmSelect.render({
                el: '#address',
                toolbar: {
                    show: true,
                },
                filterable: true,
                paging: true,
                pageSize: 10,
                data: [],
                radio: true,
                clickClose: true,
                tips: '请输入搜索',
                name: 'address',
                remoteSearch: true,
                remoteMethod: function (val, cb, show) {
                    //这里如果val为空, 则不触发搜索
                    if (!val) {
                        return cb([]);
                    }
                    let obj_pro = xmSelect.get('#province', true);

                    $.get("/admin/system.address/getShopByAddress", {
                        keywords: val,
                        city: obj_pro.getValue('nameStr')
                    }).then(res => {
                        if (res.code === 1) {
                            console.log(res.data)
                            cb(res.data)
                        } else {
                            layer.msg(res.msg)
                        }
                    })
                },
                on: function (data) {
                    console.log(data)
                    let arr = data.arr,
                        isAdd = data.isAdd;
                    if (isAdd) {
                        if (arr.length != 0) {
                            $("#lat").val(arr[0].lat);
                            $("#lng").val(arr[0].lng);
                        }
                    }
                }

            })
            $.get("/admin/system.province/getProvinceByList").then(res => {
                if (res.code === 1) {
                    province.update({
                        data: res.data
                    })
                }
            })
            ea.listen();
        },
        edit: function () {
            //获取分组
            let machine_cate = xmSelect.render({
                el: '#machine_cate',
                radio: true,
                clickClose: true,
                toolbar: {show: true},
                name: 'machine_cate',
                paging: true,
                filterable: true,
                tips: '选择机器分组',
                data: [],
            });
            //获取支付方式
            $.get("/admin/machine.cate/getCateByList").then(res => {
                if (res.code == 1) {
                    machine_cate.update({
                        data: res.data,
                        initValue:[machine_cate_row]
                    })
                }
            });


            let province = xmSelect.render({
                el: '#province',
                toolbar: {
                    show: true,
                },
                filterable: true,
                paging: true,
                pageSize: 10,
                data: [],
                radio: true,
                clickClose: true,
                name: 'province',
                on: function (data) {
                    console.log(data)
                    let arr = data.arr,
                        isAdd = data.isAdd;
                    if (isAdd) {
                        $("#province_name").val(arr[0].name);
                        $.get("/admin/system.city/getProvinceByCityNameAndValue", {
                            province: arr[0].value
                        }).then(res => {
                            if (res.code == 1) {
                                city.update({
                                    data: res.data
                                })
                            }
                        })
                    }
                }
            })
            let city = xmSelect.render({
                el: '#city',
                toolbar: {
                    show: true,
                },
                filterable: true,
                paging: true,
                pageSize: 10,
                data: [],
                radio: true,
                clickClose: true,
                tips: '请选择省',
                name: 'city',
                on: function (data) {
                    let arr = data.arr,
                        isAdd = data.isAdd;
                    if (isAdd) {
                        $("#city_name").val(arr[0].name);
                        $.get("/admin/system.area/getCityByAreaNameAndValue", {
                            city: arr[0].value
                        }).then(res => {
                            if (res.code == 1) {
                                area.update({
                                    data: res.data
                                })
                            }
                        })
                    }
                }
            })
            let area = xmSelect.render({
                el: '#area',
                toolbar: {
                    show: true,
                },
                filterable: true,
                paging: true,
                pageSize: 10,
                data: [],
                radio: true,
                clickClose: true,
                tips: '请选择市',
                name: 'area',
                on: function (data) {
                    let arr = data.arr,
                        isAdd = data.isAdd;
                    if(isAdd) {
                        $("#area_name").val(arr[0].name);
                    }
                }
            })
            let address = xmSelect.render({
                el: '#address',
                toolbar: {
                    show: true,
                },
                filterable: true,
                paging: true,
                pageSize: 10,
                data: [],
                radio: true,
                clickClose: true,
                tips: '请输入搜索',
                name: 'address',
                remoteSearch: true,
                remoteMethod: function (val, cb, show) {
                    //这里如果val为空, 则不触发搜索
                    if (!val) {
                        return cb([]);
                    }
                    let obj_pro = xmSelect.get('#province', true);

                    //这里引入了一个第三方插件axios, 相当于$.ajax
                    $.get("/admin/system.address/getShopByAddress", {
                        keywords: val,
                        city: obj_pro.getValue('nameStr')
                    }).then(res => {
                        if (res.code === 1) {
                            console.log(res.data)
                            cb(res.data)
                        }
                    })
                },
                on: function (data) {
                    console.log(data)
                    let arr = data.arr,
                        isAdd = data.isAdd;
                    if (isAdd) {
                        if (arr.length != 0) {
                            $("#lat").val(arr[0].lat);
                            $("#lng").val(arr[0].lng);
                        }
                    }
                }

            })
            $.get("/admin/system.province/getProvinceByList").then(res => {
                if (res.code === 1) {
                    province.update({
                        data: res.data
                    })
                }
            })

            ea.listen();
        },
        authorization:function () {

            ea.listen();
        },
        dialog:function () {
            let isInputVal = false
            var cls = '' //点击时父级的class
            let moke = [];

            let request = getRequest();

            cls = request['cls'];

            function queryClassif() { // 请求分类 后端接口

                let html = ''
                ea.request.post(
                    {
                        url: '/admin/mall.specs/getSpecsList',
                    }, function (res) {
                        res.data.forEach(function (item, index) {
                            html += `<li class="child-ele" data-id="${item.id}"  data-index="${index}">${item.title}</li>`
                        })
                        $('.spec-left').html(html)
                    }
                );
            }

            queryClassif(); // 获取后端分类数据

            //  点击获取而已
            $('body').on('click', '.child-ele', function () {

                $(this).parent().children('li').removeClass('layui-btn-normal');
                $(this).addClass('layui-btn-normal');

                let index = $(this).attr('data-index');
                specs_id = $(this).attr('data-id');
                // let projectArr = moke[index]['project'].split(',')

                let url = "/admin/mall.specsValue/getBySpecsId" + "?specs_id=" + specs_id;

                ea.request.get({
                    url: url
                }, function (res) {
                    let html = ''
                    let projectArr = res.data;
                    projectArr.forEach(function (item) {
                        html += '<button type="button" data-specs-value-id="' + item.id + '" class="layui-btn layui-btn-sm layui-btn-normal" style="margin-top: 12px"> <b>' + item.title + '</b><i class="layui-icon del-child-tags" style="padding-left: 12px;"></i></button>'
                    })
                    $specleft = $('.spec-right')
                    $($specleft).html(html)
                });

                isInputVal = true
                // let html = ''
                // projectArr.forEach(function (item, index) {
                //     html += '<button type="button" class="layui-btn layui-btn-sm layui-btn-normal" style="margin-top: 12px"> <b>' + item + '</b><i class="layui-icon del-child-tags" style="padding-left: 12px;"></i></button>'
                // })
                // $specleft = $('.spec-right')
                // $($specleft).html(html)
            })

            // 删除规格值按钮
            $('html').on('click', '.del-child-tags', function () {
                $(this).parent().remove()
                // var index = parent.layer.getFrameIndex(window.name);
                // parent.layer.close(index);
            })

            // 添加规格标签
            $('#add-spec-tags').on('keypress', function (e) {

                if (!isInputVal) {
                    return layer.msg('请点选左侧规格名称')
                }
                if (e.which === 13) {
                    let tags = $(this).val();
                    let url = "/admin/mall.specsValue/save?specs_id=" + specs_id + "&name=" + tags;
                    ea.request.get({
                        url: url
                    }, function (res) {
                        if (res.code != 1) {
                            layer.msg("添加失败，请稍候重试");
                            return false;
                        }
                        let tag = '<button type="button" data-specs-value-id="' + res.data.id + '" class="layui-btn layui-btn-sm layui-btn-normal" style="margin-top: 12px"><b>' + tags + '</b> <i class="layui-icon del-child-tags" style="padding-left: 12px;"></i></button>'
                        $('.spec-right').append(tag)
                        $(this).val('');
                    });

                }
            })


            // 提交规格值到商品页面
            $('html').on('click', '.classify-btn', function () {
                let spec_left_name = '';
                let spec_left_id = 0;
                // 左侧规格类目
                let spec_left = $('.spec-left').children('li')
                spec_left.each(function (index, item) {
                    if ($(item).hasClass('layui-btn-normal')) {
                        spec_left_name = $(item).text()
                        spec_left_id = $(item).attr('data-id')
                    }
                })

                // 右侧规格值
                let spec_right = $('.spec-right').find('button')
                let tmp = ''
                let spec_tmp = ''

                spec_right.each(function (index, item) {
                    let name = $(item).children('b').text()
                    let specs_value_id = $(item).attr('data-specs-value-id');
                    tmp += `<li class="layui-badge layui-bg-blue">${name}</li>`
                    //spec_tmp += `<li><label><input type="checkbox"  class="sku_value" lay-ignore  propvalid="${specs_value_id}" value="${name}"/>${name}</label></li>`
                    if(`${name}` == '自选') {
                        //口味自定义
                        spec_tmp += `${name}
                            
                            <div style="display: flex;flex-direction: row;align-items: center">
                            
                            <span>参数：<input type="text" name="items[${specs_value_id}][value]" class="layui-input" lay-verify="required" required value="" placeholder="请输入参数" style="width:100px;margin-left: 10px;"></span>
                            <span>库存：<input type="text" name="items[${specs_value_id}][stock]" class="layui-input" lay-verify="required" required value="" placeholder="请输入库存" style="width:100px;margin-left: 10px;"></span>
                            <span><input type="hidden" name="items[${specs_value_id}][hot]" value="1" disabled></span>
                            <span>状态：<input type="checkbox" name="items[${specs_value_id}][status]" lay-skin="switch" lay-text="正常|关闭" checked></span>
                            <span>判断库存：<input type="checkbox" name="items[${specs_value_id}][is_stock]" lay-skin="switch" lay-text="是|否" checked></span>
                            <span>自选</span>
                            </div>
                            <hr/>
                        `;
                    }else {
                        spec_tmp += `${name}
                            <div style="display: flex;flex-direction: row;align-items: center">
                            <span>金额：<input type="text" name="items[${specs_value_id}][money]" class="layui-input" lay-verify="required" required value="" placeholder="请输入金额" style="width:100px;margin-left: 10px;"></span>
                            <span>库存：<input type="text" name="items[${specs_value_id}][value]" class="layui-input" lay-verify="required" required value="" placeholder="请输入参数" style="width:100px;margin-left: 10px;"></span>
                            <span>参数：<input type="text" name="items[${specs_value_id}][stock]" class="layui-input" lay-verify="required" required value="" placeholder="请输入库存" style="width:100px;margin-left: 10px;"></span>
                            <span>是否推荐：<input type="checkbox" name="items[${specs_value_id}][hot]" lay-skin="switch" lay-text="推荐|不推荐" value="1"></span>
                            <span>状态：<input type="checkbox" name="items[${specs_value_id}][status]" lay-skin="switch" lay-text="正常|关闭" checked></span>
                            <span>判断库存：<input type="checkbox" name="items[${specs_value_id}][is_stock]" lay-skin="switch" lay-text="是|否" checked></span>
                            
                            </div>
                            <hr/>
                        `;
                    }
                });
                // 给父级 赋值
                parent.$('.' + cls).find('input').val(spec_left_name)
                parent.$('.' + cls).find('input').attr('data-id', spec_left_id);
                parent.$('.' + cls).find('input').attr('data-name', spec_left_name);
                parent.$('.' + cls).find('ul').html(tmp);
                // let conf = `<ul class="SKU_TYPE del-${cls}" >
                //                     <li is_required='1' propid='${spec_left_id}' sku-type-name="${spec_left_name}"><em>*</em>${spec_left_name}</li>
                //                 </ul>
                //                 <ul class="del-${cls}">
                //                     ${spec_tmp}
                //                 </ul>
                //                 <div class="clear"></div>`
                if (spec_tmp == '') {
                    layer.msg("请选择规格值", {
                        icon: 5, shade: 0.5
                    });
                    return false;
                }
                let conf = `<tr>
                            <td data-id="${spec_left_id}">${spec_left_name}</td>
                            <td>
                                ${spec_tmp}
                            </td>
                        </tr>`

                parent.$('.skus-warp').append(conf)

                // window.parent.location.reload();//刷新父页面
                var index = parent.layer.getFrameIndex(window.name);
                parent.layui.form.render();

                parent.layer.close(index);
            })

            function getRequest() {
                let url = location.search; //获取url中"?"符后的字串
                let theRequest = {};
                if (url.indexOf("?") != -1) {
                    var str = url.substr(1);
                    strs = str.split("&");
                    for (var i = 0; i < strs.length; i++) {
                        theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
                    }
                }
                return theRequest;
            }
            ea.listen();
        },
    };
    return Controller;
});